<?php
/**
 * Created by PhpStorm.
 * User: mww
 */
namespace app\api\controller;
use think\Db;
class Match extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        extract(input());
//        if($user_id != 0){
//            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
//            if($auth == 112){
//                echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
//                exit;
//            }elseif($auth == 110){
//                echo json_encode(['status' => 302, 'msg' => $this->frost]);
//                exit;
//            }elseif($auth == 1103){
//                echo json_encode(['status' => 303, 'msg' => $this->del]);
//                exit;
//            }
//        }

    }

    /**
     * 设置赛事和国家首字母
     */
    public function setLetter()
    {
//        set_time_limit(0);
//        $citys = Db::table('up_sport_team')->select();
//        foreach ($citys as $k=>$v){
//            $str = $v['st_name_cn'];
//            $str= iconv("UTF-8","gb2312//IGNORE", $str);
//            $tmp = bin2hex(substr($str,0,1));
//            if($tmp>='B0'){ //汉字的开始
//                $t=$this->getLetter(hexdec(bin2hex(substr($str,0,2))));
//                $letter = chr($t);
//            }else{
//                $letter = mb_substr($v['st_name_cn'],0,1);
//                if($letter == '敘'){ $letter = 'X'; }
//                if($letter == '奧'){ $letter = 'A'; }
//                if($letter == '斐'){ $letter = 'F'; }
//                if($letter == '麒'){ $letter = 'Q'; }
//            }
//            $str = $v['st_country'];
//            $str= iconv("UTF-8","gb2312//IGNORE", $str);
//            $tmp = bin2hex(substr($str,0,1));
//            if($tmp>='B0'){ //汉字的开始
//                $t=$this->getLetter(hexdec(bin2hex(substr($str,0,2))));
//                $letter2 = chr($t);
//            }else{
//                $letter2 = mb_substr($v['st_country'],0,1);
//                if($letter2 == '敘'){ $letter2 = 'X'; }
//                if($letter2 == '奧'){ $letter2 = 'A'; }
//                if($letter2 == '斐'){ $letter2 = 'F'; }
//                if($letter2 == '麒'){ $letter2 = 'Q'; }
//            }
//            Db::table('up_sport_team')->where('st_id',$v['st_id'])->update([
//                'st_league_letter' => $letter,
//                'st_country_letter' => $letter2,
//            ]);
//        }
//        exit();

    }
    /**
     * 获取赛事和国家
     */
    public function getMatchScreens()
    {
        $fid = input('fid');
        if(!isset($fid) || !$fid){
            $fid = 1;
        }
        $hotdata = Db::table('up_sport_team')
            ->where('st_fid',$fid)
            ->where('st_hot',2)
            ->order('st_league_letter')
            ->field('st_league_id id,st_name_cn name,st_league_letter letter')
            ->select();
        $data = Db::table('up_sport_team')
            ->where('st_fid',$fid)
            ->order('st_league_letter')
            ->field('st_league_id id,st_name_cn name,st_league_letter letter')
            ->select();
        $start = '';
        $leagues = array();
        foreach ($data as $k=>$v){
            if($v['letter'] != $start){
                $start = $v['letter'];
            }
            $leagues[$start][] = $v;
        }
        $data = Db::table('up_sport_team')
            ->where('st_fid',$fid)
            ->group('st_country')
            ->order('st_country_letter')
            ->field('st_id id,st_country name,st_country_letter letter')
            ->select();
        $start = '';
        $countrys = array();
        foreach ($data as $k=>$v){
            if($v['letter'] != $start){
                $start = $v['letter'];
            }
            $countrys[$start][] = $v;
        }
        return json(['status'=>200,'hotdata'=>$hotdata,'msg'=>$leagues,'countrys'=>$countrys]);

    }

    /**
     * 获取赛事列表数据：
     * fid：1 足球  2篮球
     * type：0全部 1进行中 2已结束 3我的关注
     * ids：筛选赛事时，id的集合
     * names：筛选国家时，name的集合
     * page：
     */
    public function getMatchData(){
        extract(input());
//        $user_id=1;$fid=1;$type=3;$page=1;
        if(!isset($fid) || !$fid){
            $fid = 1;
        }
        $where = [
            'mf_id' => ['>',0] ,
            'mv_id' => ['>',0] ,
            'mf_fid' => $fid
        ];
        if(isset($type) && $type){
            if($type == 1) $where['mf_state'] = ['>',0];
            if($type == 2) $where['mf_state'] = -1;
            if($type == 3) {
                $mids = Db::table('up_match_love')
                    ->where('love_user_id',$user_id)
                    ->column('love_fj_matchid');
                $where['mf_fj_matchid'] = ['in',$mids];
            }
        }
        //赛事筛选
        if(isset($ids) && $ids){
            $where['mf_league_id'] = ['in',$ids];
        }
        //国家筛选
        if(isset($names) && $names){
            $cw = [
                'st_fid' => $fid,
                'st_country' => ['in',$names],
            ];
            if(isset($ids) && $ids){
                $where['st_league_id'] = ['in',$ids];
            }
            $ids2 = Db::table('up_sport_team')
                ->where($cw)
                ->column('st_league_id');
            $where['mf_league_id'] = ['in',$ids2];
        }
        $field = 'mf_id,mv_id,mf_fid,mf_state,mf_match_time,mf_name,mf_home_name_cn,mf_away_name_cn,mf_json';
        $field .= ',mf_fj_matchid,mf_league_id,mf_views';
        $match = $this->matchDatas($where,'mf_state asc,mf_match_time asc',$page,10,$field);
        if($match){
            $match = $this->dataLikes($match,$user_id,2);
            foreach ($match as $k => $v){
                $decodeData = json_decode($v['mf_json'],true);
                $match[$k]['mf_home_score'] = $decodeData['homeScore'];
                $match[$k]['mf_away_score'] = $decodeData['awayScore'];
                if($fid == 1){
                    $match[$k]['startTimeAfter'] = round((time() - strtotime($decodeData['startTime']))/60);
                    $match[$k]['homeHalfScore'] = $decodeData['homeHalfScore'];
                    $match[$k]['awayHalfScore'] = $decodeData['awayHalfScore'];
                    $match[$k]['homeCorner'] = $decodeData['homeCorner'];
                    $match[$k]['awayCorner'] = $decodeData['awayCorner'];
                }else{
                    $match[$k]['remainTime'] = $decodeData['remainTime'];
                    $match[$k]['home1'] = $decodeData['home1'];
                    $match[$k]['home2'] = $decodeData['home2'];
                    $match[$k]['home3'] = $decodeData['home3'];
                    $match[$k]['home4'] = $decodeData['home4'];
                    $match[$k]['away1'] = $decodeData['away1'];
                    $match[$k]['away2'] = $decodeData['away2'];
                    $match[$k]['away3'] = $decodeData['away3'];
                    $match[$k]['away4'] = $decodeData['away4'];
                }
            }
        }
        return json(['status'=>200,'msg'=>$match]);
    }
    /**
     * 赛事详情：discussInfo
     * mf_fj_matchid
     */
    public function MatchInfo(){
        extract(input());
        $data = $this->getTableData('up_match_fj',['mf_fj_matchid' => $mf_fj_matchid]);
        $fff = 'mv_live_url1,mv_live_url2,mv_live_url3,mv_live_status,mv_status';
        $data2 = $this->getTableData('up_match_live',['mv_id' => $mv_id],$fff,2);

        //----------------------处理数据start-------------------------------------------------
        $decodeData = json_decode($data['mf_json'],true);
        $data['mf_home_score'] = $decodeData['homeScore'];
        $data['mf_away_score'] = $decodeData['awayScore'];
        if($data['mf_fid'] == 1){
            $data['startTimeAfter'] = round((time() - strtotime($decodeData['startTime']))/60);
            $data['homeHalfScore'] = $decodeData['homeHalfScore'];
            $data['awayHalfScore'] = $decodeData['awayHalfScore'];
            $data['homeCorner'] = $decodeData['homeCorner'];
            $data['awayCorner'] = $decodeData['awayCorner'];
        }else{
            $data['remainTime'] = $decodeData['remainTime'];
            $data['home1'] = $decodeData['home1'];
            $data['home2'] = $decodeData['home2'];
            $data['home3'] = $decodeData['home3'];
            $data['home4'] = $decodeData['home4'];
            $data['away1'] = $decodeData['away1'];
            $data['away2'] = $decodeData['away2'];
            $data['away3'] = $decodeData['away3'];
            $data['away4'] = $decodeData['away4'];
        }
        //----------------------处理数据 end -------------------------------------------------
        if(!isset($type) || !$type){
            $type = 0;
        }
        $battlesData = [];
        $userdata = [];
        if($type == 0) {
            //-------------浏览量+1----------------
            Db::table('up_match_fj')->where('mf_fj_matchid', $mf_fj_matchid)->setInc('mf_views');
            //-------------浏览量+1----------------

            $zan = $this->getTableData('up_match_love', ['love_user_id' => $user_id, 'love_fj_matchid' => $mf_fj_matchid]);
            $data['like'] = 1; //我没有赞
            if ($zan) {
                $data['like'] = 2;
            }
            $data['league_logo'] = Db::table('up_sport_team')
                ->where('st_fid', $data['mf_fid'])
                ->where('st_league_id', $data['mf_league_id'])
                ->value('st_logo');
            $data['home_logo'] = Db::table('up_sport')
                ->where('sport_fid', $data['mf_fid'])
                ->where('sport_team_id', $data['mf_home_id'])
                ->value('sport_logo');
            $data['away_logo'] = Db::table('up_sport')
                ->where('sport_fid', $data['mf_fid'])
                ->where('sport_team_id', $data['mf_away_id'])
                ->value('sport_logo');
            //数据分析
            $fid = $data['mf_fid'];
            if($fid == 1){
                $url1 = 'http://interface.win007.com/football/analy.aspx?matchId=' . $mf_fj_matchid;
                $data_result1 = file_get_contents($url1);
                $battles = json_decode($data_result1, true);
                if($battles && $battles['list'][0]['headToHead']){
                    foreach ($battles['list'][0]['headToHead'] as $k => $v) {
                        $v_arr = explode('^',$v[0]);
                        $battlesData[$k]['mf_name'] = explode(',',$v_arr[1])[0];
                        $battlesData[$k]['mf_match_time'] = $v_arr[2];
                        $battlesData[$k]['mf_home_name_cn'] = explode(',',$v_arr[4])[0];
                        $battlesData[$k]['mf_away_name_cn'] = explode(',',$v_arr[5])[0];
                        $battlesData[$k]['mf_home_score'] = $v_arr[6];
                        $battlesData[$k]['mf_away_score'] = $v_arr[7];
                        $battlesData[$k]['homeHalfScore'] = $v_arr[8];
                        $battlesData[$k]['awayHalfScore'] = $v_arr[9];
                        $battlesData[$k]['homeCorner'] = $v_arr[12];
                        $battlesData[$k]['awayCorner'] = $v_arr[13];
                    }
                }
            }
            //专家号
            $field = 'user_id,user_username,user_image,user_title,user_tags';
            $userdata = Db::table('up_u_user')
                ->where('user_auth', $fid)
                ->where('user_status', 1)
                ->order('user_hot desc')
                ->field($field)
                ->select();
            if ($userdata) {
                $userdata = $this->dataLikes($userdata, $user_id);
            }
        }
        return json(['status'=>200,'msg'=>$data,'livedata'=>$data2,'battles'=>$battlesData,'userdata'=>$userdata]);
    }
    /**
     * 查看讨论
     * mf_fj_matchid
     * mt_id
     * @return mixed|\think\response\Json
     */
    public function matchTalks(){
        extract(input());
        $where = [
            'mt_fj_matchid' => $mf_fj_matchid
        ];
        if(isset($mt_id) && $mt_id && $mt_id > 0){
            $where['mt_id'] = ['>' , $mt_id];
        }
        $field = 'mt.*,user_username,user_image';
        $reply = Db::table('up_match_talk')->alias('mt')
            ->join('up_u_user u','mt.mt_user_id = u.user_id','left')
            ->where($where)
            ->order('mt_id asc')
            ->field($field)
            ->select();
        return json(['status'=>200 , 'msg'=>$reply]);
    }
    /**
     * 查看直播文字
     * mf_fj_matchid
     * mtf_id
     * @return mixed|\think\response\Json
     */
    public function matchTextLive(){
        extract(input());
        $data = $this->getTableData('up_match_fj',['mf_fj_matchid' => $mf_fj_matchid],'mf_echarts',2);
        $data['echLeft1'] = 0;
        $data['echLeft2'] = 0;
        $data['echMiddle1'] = 0;
        $data['echMiddle2'] = 0;
        $data['echRight1'] = 0;
        $data['echRight2'] = 0;
        if($data['mf_echarts']){
            //43.进攻  44.危险进攻   14.控球率
            $arrAll = explode(';',$data['mf_echarts']);
            foreach ($arrAll as $k => $v){
                $arrSon = explode(',',$v);
                if($arrSon[0] == 14){
                    $data['echRight1'] = str_replace('%','',$arrSon[1]);
                    $data['echRight2'] = str_replace('%','',$arrSon[2]);
                }
                if($arrSon[0] == 43){
                    $data['echLeft1'] = $arrSon[1];
                    $data['echLeft2'] = $arrSon[2];
                }
                if($arrSon[0] == 44){
                    $data['echMiddle1'] = $arrSon[1];
                    $data['echMiddle2'] = $arrSon[2];
                }
            }
        }
        $where = [
            'mtf_fj_matchid' => $mf_fj_matchid
        ];
        if(isset($mtf_id) && $mtf_id && $mtf_id > 0){
            $where['mtf_id'] = ['>' , $mtf_id];
        }
        $field = 'mtf_id,mtf_content';
        $reply = Db::table('up_match_talk_fj')
            ->where($where)
            ->order('mtf_id asc')
            ->field($field)
            ->select();
        return json(['status'=>200 , 'msg'=>$reply , 'info'=>$data]);
    }
    /**
     * 赛事讨论-发布
     */
    public function matchTalksAdd(){
        extract(input());
        $today = date('Y-m-d H:i:s');
        $data = [
            'mt_fj_matchid' => $mf_fj_matchid,
            'mt_user_id' => $user_id,
            'mt_content' => $content,
            'mt_time' => $today,
        ];
        $res = Db::table('up_match_talk')->insert($data);
        if($res){
            return json(['status'=>200,'msg'=>'发表成功！']);
        }else{
            return json(['status'=>100,'msg'=>'发表失败，请重试！']);
        }
    }
    /**
     * 关注和取消关注
     *
     */
    public function dianzan(){
        extract(input());
        $today = date('Y-m-d H:i:s');
        $have = $this->getTableData('up_match_love',['love_user_id' => $user_id,'love_fj_matchid' => $mf_fj_matchid]);
        if($have){
            $res = Db::table('up_match_love')->where('love_id',$have['love_id'])->delete();
        }else{
            $res = Db::table('up_match_love')->insert([
                'love_user_id' => $user_id,
                'love_fj_matchid' => $mf_fj_matchid,
                'love_time' => $today
            ]);
        }
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }
}